package com.cygsunri.consumption.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cygsunri.consumption.entity.EnergyItem;
import com.cygsunri.consumption.mapper.EnergyItemMapper;
import com.cygsunri.consumption.service.EnergyItemService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class EnergyItemServiceImpl extends ServiceImpl<EnergyItemMapper, EnergyItem> implements EnergyItemService {

    @Autowired
    private EnergyItemMapper energyItemMapper;

    @Override
    public EnergyItem getEnergyItemById(String id) {
        QueryWrapper<EnergyItem> queryWrapper = new QueryWrapper<EnergyItem>()
                .eq("id", id);
        return energyItemMapper.selectOne(queryWrapper);
    }

    @Override
    public List<EnergyItem> getEnergyItemByBuildingAndEnergySort(String buildingId, String energySort) {
        return energyItemMapper.getEnergyItemByBuildingAndEnergySort(buildingId, energySort);
    }

    @Override
    public List<EnergyItem> getEnergyItemByAccountAndEnergySort(String accountID, String energySort) {
        return energyItemMapper.getEnergyItemByAccountAndEnergySort(accountID, energySort);
    }

    @Override
    public List<EnergyItem> sortEnergyItems(List<EnergyItem> energyItems){
        List<EnergyItem> resultList = new ArrayList<>();
        for (EnergyItem EnergyItem : energyItems) {
            if (StringUtils.isBlank(EnergyItem.getParent())) {
                resultList.add(EnergyItem);
                findChildren(EnergyItem, energyItems);
            }
        }
        return resultList;
    }

    /**
     * 递归查询下级分类
     */
    private void findChildren(EnergyItem parent, List<EnergyItem> EnergyItems) {
        List<EnergyItem> childrenList = new ArrayList<>();

        for (EnergyItem d : EnergyItems) {
            if (Objects.equals(parent.getId(), d.getParent())) {
                childrenList.add(d);
                findChildren(d, EnergyItems);
            }
        }

        if (childrenList.isEmpty()) {
            return;
        }
        parent.setChildren(childrenList);
    }
}
